package com.codefalse.mybatis.generator.util;

import com.alibaba.fastjson.JSON;
import com.codefalse.mybatis.generator.constant.SQLiteConstants;
import com.codefalse.mybatis.generator.model.GenerateConfigModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;

/**
 * @author songxiangfeng
 * Created At 2020-01-14 14:15
 */
@Slf4j
public final class SQLiteUtils {

    private static JdbcTemplate jdbcTemplate;

    private SQLiteUtils(){}

    public static void initJdbcTemplate(JdbcTemplate jdbcTemplate) {
        SQLiteUtils.jdbcTemplate = jdbcTemplate;
    }

    /**
     * 查询连接配置
     * @return
     */
    public static List<String> selectConnectionNames() {
        return jdbcTemplate.queryForList(SQLiteConstants.SELECT_CONNECTION_NAME, String.class);
    }

    /**
     * 查询数据库下保存的项目路径
     * @param configName
     * @param database
     * @return
     */
    public static List<Map<String, Object>> selectProjects(String configName, String database) {
        return jdbcTemplate.queryForList(SQLiteConstants.SELECT_PROJECTS, configName, database);
    }

    /**
     * 保存或者更新项目配置
     * @param configName
     * @param database
     * @param model
     */
    public static void saveOrUpdateProject(String configName, String database, GenerateConfigModel model) {
        log.debug("保存或者更新项目配置");
        Integer count = jdbcTemplate.queryForObject(SQLiteConstants.EXISTS_PROJECT, Integer.class, configName, database, model.getProjectPath());
        if (count > 0) {
            jdbcTemplate.update(SQLiteConstants.UPDATE_PROJECT, JSON.toJSONString(model), configName, database, model.getProjectPath());
            return;
        }
        String formatSql = String.format(SQLiteConstants.INSERT_PROJECT, configName, database, model.getProjectPath(), JSON.toJSONString(model));
        jdbcTemplate.execute(formatSql);
    }

}
